package com.itheima.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.*;

public class CodeUtils {
    private static String SIGHKEY = "itheima";
    private static List<String> jwts = new ArrayList<>();
    public static String generateCode(String phone) {
        Random r = new Random();
        char[] c = new char[6];
        for (int i = 0; i < 6; i++) {
            c[i] = (char) (r.nextInt(10) + '0');
        }
        String code = new String(c);
        System.out.println("code:" + code);
        Map<String, Object> claims = new HashMap<>();
        claims.put("code", code);
        claims.put("phone", phone);
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, SIGHKEY)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() +600 * 1000))
                .compact();
        jwts.add(jwt);
        return code;
    }

    public static Claims parseCode(String code, String phone) {
        for (int i = 0; i < jwts.size(); i++) {
            try {
                Claims claims = JwtUtils.parseJWT(jwts.get(i));
                System.out.println(claims);
                if (claims.get("code").equals(code) && claims.get("phone").equals(phone)) {
                    jwts.remove(i);
                    System.out.println("验证成功");
                    return claims;
                }
            } catch (Exception ignored) {
                jwts.remove(i);
            }
        }
        return null;
    }
}
